import java.util.LinkedList;
import java.util.Queue;

class Solution {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int maxDistance(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dis = new int[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                dis[i][j] = -1;
            }
        }
        Queue<int[]> queue = new LinkedList<>();
        for(int i = 0; i < m ; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    queue.offer(new int[] {i, j});
                    dis[i][j] = 0;
                }
            }
        }
        int ret = -1;
        while(!queue.isEmpty()){
            int[] point = queue.poll();
            int a = point[0];
            int b = point[1];
            for(int i = 0; i < 4; i++){
                int x = a + dx[i];
                int y = b + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n && dis[x][y] == -1){
                    queue.offer(new int[] {x, y});
                    dis[x][y] = dis[a][b] + 1;
                    ret = Math.max(ret, dis[x][y]);
                }
            }
        }
        return ret;
    }
}